import random
import sys
import os
import time
from prompt_toolkit import prompt as gInput


def gnuInput(message):
    return gInput(message, multiline=False, refresh_interval=2)


rootDir = os.path.abspath(os.path.join(__file__, r"..\.."))

sys.path.append(rootDir)
# print(sys.path, "<---sys.path")

from config import config
from PyInquirer import prompt
from simple_chalk import chalk
from argparse import ArgumentParser

from helper.pronounce import playPronounce
import helper.sound as sound
from helper.db import writeTestData
from helper.daily import createBookDailyFiles
from helper.phonetic import autoAddPhonetic
from newWords.index import appendNewWords


import common.index as common


def showHelp():
    helpInfo = """
    :: 若已经定义别名 wtest='pyton wordstest.py' 则用法如下：
    语法: wtest [date/num] [isLianXi]
    例子:
    1. wtest # 显示帮助信息
    2. wtest 0 # 测试今天的单词
    3. wtest 0 y # 练习今天的单词
    4. wtest -1 # 测试昨天的单词
    5. wtest -1 y # 练习昨天的单词
    6. wtest 1 y # 练习明天的单词
    7. wtest 0802 # 测试8月2日的单词
    8. wtest c # 继续上一次通过记录测试
    """
    if len(sys.argv) == 1:
        print(helpInfo)
        sys.exit(1)


def getWList(ls, sep=None):
    wordsstr = " ".join(ls)
    wlist = wordsstr.split(sep)
    wlist = [val.replace("/", "").replace("_", " ") for val in wlist]
    wlist = [val for val in wlist if val]
    return wlist


def getThreeList():
    chineseLines = []
    englishLines = []
    yinbiaoLines = []

    lines = common.getDailyFileContent(
        args.get("book"), args.get("dailyFileSn"), config
    )

    for i, line in enumerate(lines):
        yushu = i % 3
        if yushu == 0:
            chineseLines.append(line.strip("\n"))
        elif yushu == 2:
            yinbiaoLines.append(line.strip("\n"))
        else:
            englishLines.append(line.strip("\n"))

    # print(chinese,english,yinbiao)

    ylist = getWList(yinbiaoLines, "/ /")
    clist = getWList(chineseLines)
    elist = getWList(englishLines)

    # print(clist, len(clist))
    # print(elist, len(elist))
    # print(ylist, len(ylist))
    # sys.exit()

    return clist, elist, ylist


def getNewList(errList):
    repeatTimes = config.get("errorWordRepeat")
    uniqErrLs = list(set(errList))  # 去重后的列表
    newList = sorted(uniqErrLs * repeatTimes)
    return newList


def inputUser():
    userName = gnuInput("请输入用户名：")
    return userName


def checkAnswer(userInput, answer):
    userInput = userInput.replace(" ", "").replace("\t", "").lower()
    answer = answer.replace(" ", "").replace("\t", "").lower()
    return userInput == answer


startTime = common.getNow()


def startTest(cnKeys, wdict, ybdict):
    print(chalk.bgGray("(按a查看答案, 按y查看音标, 按s跳过, 按x退出, 空格个数不限)"))

    hasSeeOrSkip = False
    rightTimes = 0
    errList = []

    while True:
        cnKey = cnKeys[rightTimes]
        answer = wdict[cnKey]
        yinbiao = ybdict[cnKey]
        hasSpace = answer.count(" ") > 0

        if hasSpace:
            chineseOutPut = cnKey + "(词组)"
        else:
            chineseOutPut = cnKey

        percent = common.percentStr(rightTimes + 1, len(cnKeys))
        # 测试模式：显示进度 和 中文
        if args.get("isTest"):
            userAnswer = gnuInput("%s %s: " % (percent, chineseOutPut))
        else:
            # 练习模式： 进度 和 中文 英文 音标
            # answer = input('%d/%d %s \n     %s [%s]\n     :' %(rightTimes + 1,len(wkeys), chineseOutPut, daan, yinbiao ))
            userAnswer = gnuInput(
                "%s %s \n     [%s] %s\n     :"
                % (
                    percent,
                    chineseOutPut,
                    yinbiao,
                    answer,
                )
            )

        userAnswer = normalize(userAnswer)

        if not userAnswer.strip():
            continue

        playSeconds = (
            config.get("pronounceSeconds")
            if len(answer) > 6
            else config.get("pronounceSeconds") - 0.5
        )
        if checkAnswer(userAnswer, answer):
            common.headLogSuc(yinbiao if args.get("isTest") else "", "Yes!", 9)
            playPronounce(answer, playSeconds)
            rightTimes += 1
            # sound.playGood()
        elif userAnswer.upper() == "X":
            sys.exit(0)
        elif userAnswer.upper() == "A":
            hasSeeOrSkip = True
            common.headLogInfo("%s [%s]" % (answer, yinbiao), "Answer:", 12)
            errList.append(cnKey)
        elif userAnswer.upper() == "S":
            hasSeeOrSkip = True
            common.headLogInfo(yinbiao, "Info:", 10)
            rightTimes += 1
        elif userAnswer.upper() == "Y":
            common.headLogInfo("/ %s / " % (yinbiao), "Phonetic:", 14)
        else:
            common.headLogErr("", "No!", 8)
            sound.playBad()
            errList.append(cnKey)

        if rightTimes >= len(cnKeys):
            print("The End~~")

            common.savePassResultToFile(
                args.get("user"),
                args.get("book"),
                args.get("dailyFile"),
                args.get("isTest"),
                config,
            )

            if not args.get("isTest"):
                isPass = None
            else:
                isPass = not hasSeeOrSkip and not len(errList)

            if isPass:
                writeTestData(
                    args.get("user"),
                    startTime,
                    args.get("dailyFile"),
                    "word",
                    args.get("book"),
                )

                print("%s pass the test and save." % (args.get("user")))
                # print(userName,startTime,testingFile,'*****************')

            if len(errList) == 0:
                sound.playWin()
                break
            else:
                sound.playTips()
                startTest(getNewList(errList), wdict, ybdict)
                break


def normalize(userAnswer):
    while True:
        if userAnswer.count("  ") < 1:
            break
        userAnswer = userAnswer.replace("  ", " ")
    return userAnswer


def delSpace(userAnswer, rightAnswer):
    if rightAnswer.count(" ") == 0:
        userAnswer = userAnswer.replace(" ", "")
    return userAnswer


def main():
    hasPronounceDir = os.path.exists("./pronounce")
    if not hasPronounceDir:
        os.mkdir("./pronounce")

    clist, elist, ylist = getThreeList()
    wdict = dict(zip(clist, elist))
    ybdict = dict(zip(clist, ylist))

    cnKeys = list(wdict.keys())

    random.shuffle(cnKeys)

    # wkeys = wkeys[0:3] # for test

    testCnKeys = []
    # 练习模式，每个单词练习两遍
    if not args.get("isTest"):
        for cnkey in cnKeys:
            testCnKeys.extend([cnkey] * config.get("testWordRepeat"))
    else:
        testCnKeys = cnKeys

    startTest(testCnKeys, wdict, ybdict)
    # test(mywkeys[:2])


def startAdmin():
    os.system("")

    print(cargs, "<----cargs")

    books = common.getBooks(config)
    if not cargs.book in books:
        print(chalk.yellow("单词合集 %s 不存在，可选合集如下:" % cargs.book))
        print(books)
        sys.exit(1)

    print()
    if cargs.action == "create":
        createBookDailyFiles(cargs.book, config)
    elif cargs.action == "yinbiao":
        autoAddPhonetic(cargs.book, config)
    elif cargs.action == "daily":
        # 在 newWords/temp.txt 添加完单词，执行 wtest daily -b PET
        success = appendNewWords(cargs.book)
        if success:
            createBookDailyFiles(cargs.book, config)
            autoAddPhonetic(cargs.book, config)
            sys.exit(0)
        else:
            sys.exit(1)


# showHelp()

# print("按A显示答案，按Y显示音标。")

# userName = inputUser()
# testingFile = getFileName(userName)


# isLianXiMode = False
# if len(sys.argv) > 2:
#     isLianXiMode = sys.argv[2] in ["1", "y", "yes", "true", "True"]


# DQuser = None
# startTime = getNowDateTime()

lastResult = common.getLastResult(config)
print("------------>lastResult", lastResult)
args = {}
cargs = {}

# see help message
# wtest -h  # wtest is an alias of index.py
if __name__ == "__main__":
    if len(sys.argv) == 1:
        # usage: wtest or python index.py
        # start word test or practice
        args = common.getArgsByQuestions(lastResult, config, "单词")

        main()
    else:
        # wtest daily -b FCE or python index.py daily -b FCE
        # start manage word books, add daily words
        cargs = common.getCliArgs("单词")
        # print(cargs, '<----')
        print(cargs.book, '<--cargs.book')
        startAdmin()


# print(del_space('a a a a','aaaa'))
